package com.red.wood.module.eval.dao.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.red.wood.common.springjdbc.SqlServerDao;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.DateUtil;
import com.red.wood.common.util.IMap;
import com.red.wood.module.eval.dao.EvalReportInfoDao;
import com.red.wood.module.eval.mybatis.service.EvalPassEnterpriseService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Repository
public class EvalReportInfoDaoImpl implements EvalReportInfoDao{

	private static final Log log = LogFactory.getLog(EvalReportInfoDaoImpl.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private SqlServerDao sqlServerDao;
	
	@Value("${deptPerson}")
	private String deptPerson;
	
	@Value("${personTel}")
	private String personTel;
	
	@Override
	public Map<String,Object> getIdcNotInterReport(String evalNum,String userId){
		Map<String,Object> datas = new HashMap<String,Object>();
		
		Map<String,Object> masterInfo = queryMasterByEvalNum(evalNum);
		
		List<Map<String,Object>> houseList = queryForHouseInfo(evalNum,userId);
		
		Map<String,Object> houseInfo = new HashMap<String,Object>();
		if(!houseList.isEmpty()) {
			houseInfo = houseList.get(0);
		}
		
		List<Map<String,Object>> linkInfo = queryForLinkInfo(evalNum,userId);
		if(!linkInfo.isEmpty()) {
			double total = 0;
			StringBuffer linkTypeStr = new StringBuffer("链路信息（"); 
			for(Map<String,Object> map : linkInfo) {
				String link_type = CommonUtils.valueOf(map.get("link_type"));
				linkTypeStr.append(link_type).append("/");
				String link_bandwidth = CommonUtils.valueOf(map.get("link_bandwidth"));
				if(StringUtils.isNotBlank(link_bandwidth)) {
					//可能会出现科学计数法
					BigDecimal bigDecimal = new BigDecimal(link_bandwidth);
					double bandwidth = Double.parseDouble(bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
					total = total + bandwidth;
				}
			}
			linkTypeStr.delete(linkTypeStr.length()-1, linkTypeStr.length());
			linkTypeStr.append("）").append(total).append("Gbps");
			
			houseInfo.put("linkTypeAndGbps", linkTypeStr.toString());
		}
		
		datas.put("data", masterInfo);
		datas.put("adoptNotIntData", houseInfo);
		
		return datas;
	}
	
	@Override
	public Map<String,Object> getIdcOnlyInterReport(String evalNum,String userId){
		Map<String,Object> datas = new HashMap<String,Object>();
		
		Map<String,Object> masterInfo = queryMasterByEvalNum(evalNum);
		
		List<Map<String,Object>> houseList = queryForHouseInfo(evalNum,userId);
		
		//机房信息
		List<Map<String,Object>> houseDataList = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map : houseList) {
			Map<String,Object> houseData = new HashMap<String,Object>();
			houseData.put("nodeName", map.get("houseName"));
			houseData.put("houseAddr", map.get("houseAddress"));
			houseDataList.add(houseData);
		}
		
		List<Map<String,Object>> linkInfo = queryForLinkInfo(evalNum,userId);
		
		//链路信息
		List<Map<String,Object>> gbpsDataList = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map : linkInfo) {
			Map<String,Object> gbpsData = new HashMap<String,Object>();
			String link_bandwidth = CommonUtils.valueOf(map.get("link_bandwidth"));
			gbpsData.put("province", map.get("link_province"));
			gbpsData.put("type", map.get("link_type"));
			if(StringUtils.isNotBlank(link_bandwidth)) {
				//可能会出现科学计数法
				BigDecimal bigDecimal = new BigDecimal(link_bandwidth);
				link_bandwidth = bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
			}
			gbpsData.put("gbps", link_bandwidth);
			gbpsDataList.add(gbpsData);
		}
		
		datas.put("data", masterInfo);
		datas.put("houseData", houseDataList);
		datas.put("gbpsData", gbpsDataList);
		return datas;
	}
	
	@Override
	public Map<String, Object> getCdnReport(String evalNum, String userId) {
		Map<String,Object> datas = new HashMap<String,Object>();
		
		Map<String,Object> masterInfo = queryMasterByEvalNum(evalNum);
		
		List<Map<String,Object>> houseList = queryForHouseInfo(evalNum,userId);
		
		//机房信息
		List<Map<String,Object>> houseDataList = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map : houseList) {
			Map<String,Object> houseData = new HashMap<String,Object>();
			houseData.put("nodeName", map.get("houseName"));
			houseData.put("houseAddr", map.get("houseAddress"));
			houseDataList.add(houseData);
		}
		
		List<Map<String,Object>> linkInfo = queryForLinkInfo(evalNum,userId);
		
		//链路信息
		List<Map<String,Object>> gbpsDataList = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map : linkInfo) {
			Map<String,Object> gbpsData = new HashMap<String,Object>();
			String link_bandwidth = CommonUtils.valueOf(map.get("link_bandwidth"));
			gbpsData.put("province", map.get("link_province"));
			gbpsData.put("type", map.get("link_type"));
			if(StringUtils.isNotBlank(link_bandwidth)) {
				//可能会出现科学计数法
				BigDecimal bigDecimal = new BigDecimal(link_bandwidth);
				link_bandwidth = bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
			}
			gbpsData.put("gbps", link_bandwidth);
			gbpsDataList.add(gbpsData);
		}
		
		datas.put("data", masterInfo);
		datas.put("houseData", houseDataList);
		datas.put("gbpsData", gbpsDataList);
		return datas;
	}
	
	@Override
	public Map<String, Object> getIspReport(String evalNum, String userId) {
		Map<String,Object> datas = new HashMap<String,Object>();
		Map<String,Object> masterInfo = queryMasterByEvalNum(evalNum);
		List<Map<String,Object>> houseList = queryForHouseInfo(evalNum,userId);
		
		Map<String,Object> ispData = new HashMap<String,Object>();
		if(!houseList.isEmpty()) {
			Map<String,Object> houseInfo = houseList.get(0);
			ispData.put("gameProvince", houseInfo.get("house_province"));
			ispData.put("houseName", houseInfo.get("houseName"));
			ispData.put("houseAddress", houseInfo.get("houseAddress"));
		}
		
		List<Map<String,Object>> linkInfo = queryForLinkInfo(evalNum,userId);
		if(!linkInfo.isEmpty()) {
			double total = 0;
			for(Map<String,Object> map : linkInfo) {
				String link_bandwidth = CommonUtils.valueOf(map.get("link_bandwidth"));
				if(StringUtils.isNotBlank(link_bandwidth)) {
					//可能会出现科学计数法
					BigDecimal bigDecimal = new BigDecimal(link_bandwidth);
					double bandwidth = Double.parseDouble(bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
					total = total + bandwidth;
				}
			}
			ispData.put("gbps",total+"Gbps");
		}
		
		datas.put("data", masterInfo);
		datas.put("ispData", ispData);
		
		return datas;
	}
	
	public Map<String,Object> queryMasterByEvalNum(String evalNum){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			Date date = new Date();
			int year = DateUtil.getCurrentYear(date);
			int month = DateUtil.getCurrentMonth(date);
			int day = DateUtil.getCurrentDay(date);
			
			String sql = "select evalNum as number,enterprise_name as name,apply_business as systemName,concat_ws('',handleInfo,'Gbps') as handleInfo,contacts,moveTle from t_eval_result_query_master where evalNum = ?";
			map = jdbcTemplate.queryForMap(sql,new Object[] {evalNum});
			
			map.put("handleYear",year);
			map.put("handleMonth",month);
			map.put("handleDay",day);
			map.put("deptPerson",new String(deptPerson.getBytes("ISO-8859-1"), "UTF-8"));
			map.put("personTel",personTel);
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return map;
	}
	
	/**
	 **查询机房信息
	 * @param evalNum
	 * @param userId
	 * @return
	 */
	public List<Map<String,Object>> queryForHouseInfo(String evalNum,String userId){
		StringBuffer sql = new StringBuffer();
		
		sql.append("select evalNum,house_name as houseName,house_add as houseAddress,house_province,concat_ws('',house_province,house_city) as provinceAndCity from t_eval_result_query_house house where 1 = 1");
		sql.append(queryHouseConf(evalNum,userId));
		sql.append(" and evalNum = ?");
		
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql.toString(),new Object[] {evalNum});
		
		return list;
	}
	
	/**
	 **查询链路信息
	 * @param evalNum
	 * @param userId
	 * @return
	 */
	public List<Map<String,Object>> queryForLinkInfo(String evalNum,String userId){
		StringBuffer sql = new StringBuffer();
		sql.append("select evalNum,link_province,link_type,link_bandwidth,house_name from t_eval_result_query_link where 1 = 1");
		sql.append(queryLinkConf(userId));
		sql.append(" and evalNum = ?");
		return jdbcTemplate.queryForList(sql.toString(),new Object[] {evalNum});
	}
	
	public StringBuffer queryLinkConf(String userId){
		StringBuffer sb = new StringBuffer();
		IMap map = sqlServerDao.getEnterpriseAuthority(userId);
		
		String input = "";
		try {
			input = IOUtils.toString(EvalPassEnterpriseService.class.getClassLoader().getResourceAsStream("user_parser.json"),"UTF-8");
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		JSONArray jArray = JSONArray.fromObject(input);
		JSONObject jsonObject = jArray.getJSONObject(0);
		
		String loginUser = CommonUtils.valueOf(map.get("loginUser"));
		int userAuthority = Integer.parseInt(map.getString("userAuthority"));
		
		if(userAuthority == 4 || userAuthority == 5) {//增值企业,超级管理员
		}else {
			String value = jsonObject.getString(loginUser);
			if(userAuthority == 1) {//管局账号
				sb.append(" and link_province='"+value+"'");
			}else if(userAuthority == 2) {//集团账号(移动、电信、联通)
				sb.append(" and link_type='"+value+"'");
			}else if(userAuthority == 3) {//省级基础电信企业(分省和运营商),如北京电信
				String province = value.split("-")[0];
				String operator = value.split("-")[1];
				sb.append(" and link_province='"+province+"'");
				sb.append(" and link_type='"+operator+"'");
			}
		}
		return sb;
	}
	
	public StringBuffer queryHouseConf(String evalNum,String userId){
		StringBuffer sb = new StringBuffer();
		IMap map = sqlServerDao.getEnterpriseAuthority(userId);
		
		String input = "";
		try {
			input = IOUtils.toString(EvalPassEnterpriseService.class.getClassLoader().getResourceAsStream("user_parser.json"),"UTF-8");
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		JSONArray jArray = JSONArray.fromObject(input);
		JSONObject jsonObject = jArray.getJSONObject(0);
		
		String loginUser = CommonUtils.valueOf(map.get("loginUser"));
		int userAuthority = Integer.parseInt(map.getString("userAuthority"));
		
		if(userAuthority == 4 || userAuthority == 5) {//增值企业,超级管理员
		}else {
			String value = jsonObject.getString(loginUser);
			if(userAuthority == 1) {//管局账号
				sb.append(" and house.house_province='"+value+"'");
				sb.append(" and house.house_name in (select link.house_name from t_eval_result_query_link link where link.evalNum = '"+evalNum+"' and link.link_province = '"+value+"')");
			}else if(userAuthority == 2) {//集团账号(移动、电信、联通)
				sb.append(" and house.house_name in (select link.house_name from t_eval_result_query_link link where link.evalNum = '"+evalNum+"' and link.link_type = '"+value+"')");
			}else if(userAuthority == 3) {//省级基础电信企业(分省和运营商),如北京电信
				String province = value.split("-")[0];
				String operator = value.split("-")[1];
				sb.append(" and house.house_province='"+province+"'");
				sb.append(" and house.house_name in (select link.house_name from t_eval_result_query_link link where link.evalNum = '"+evalNum+"' and link.link_province = '"+province+"' and link.link_type = '"+operator+"')");
			}
		}
		return sb;
	}
}
